import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'
import store from '@/store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { canTurnTo } from '@/utils/access'

// 全局引用vue-router
Vue.use(Router)
NProgress.configure({ showSpinner: false }) // NProgress Configuration

// const whiteList = ['/login'] // no redirect whitelist

/**
 * Note: sub-menu only appear when route children.length >= 1
 * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 *
 * hidden: true                   if set true, item will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu
 *                                if not set alwaysShow, when item has more than one children route,
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noRedirect           if set noRedirect will no redirect in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
    roles: ['admin','editor']    control the page roles (you can set multiple roles)
    title: 'title'               the name show in sidebar and breadcrumb (recommend set)
    icon: 'svg-name'/'el-icon-x' the icon show in the sidebar
    breadcrumb: false            if set false, the item will hidden in breadcrumb(default is true)
    activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
  }
 */

// 创建route实例
const createRouter = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: routes
})

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

// 路由拦截器，引入权限管理
const turnTo = (to, access, next) => {
  var can = canTurnTo(to.name, access, routes)
  if (can) next() // 有权限，可访问
  else next({ replace: true, name: 'error_401' }) // 无权限，重定向到401页面
}

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // 设置网页标题
  document.title = getPageTitle(to.meta.title)

  // 判断用户是否登录，登录了是否有用户信息，有用户信息是否有权限访问要跳转的路由
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // 登录后，试图重定向到登录页面的，重新跳转到应用首页
      next({ path: '/' })
      NProgress.done()
    } else {
      var userInfo = store.state.user.name
      if (userInfo) {
        turnTo(to, store.state.user.access, next)
      } else {
        console.log('登录成功，已经有token，但是还没有用户信息，准备获用户信息')
        store.dispatch('user/getInfo').then(user => {
          // 拉取用户信息，通过用户权限和跳转的页面的name来判断是否有权限访问;
          // access必须是一个数组，如：['super_admin'] ['super_admin', 'admin']
          turnTo(to, user.access, next)
        }).catch(() => {
          // 获取用户信息失败，重置token
          store.dispatch('user/resetToken')
          next('/login')
        })
      }
    }
  } else {
    // 没有登录（因为没有token）

    if (to.path === '/login') {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

export default router
